﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

public partial class Business_applicationform : System.Web.UI.Page
{
    PM.PMSys.account account = new PM.PMSys.account(); //实例化account类
    PM.PMBusiness.applicationform project = new PM.PMBusiness.applicationform();//实例化project类
    PM.Model.Project newproject = null;//项目实体类
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //处理所有绑定ddl
            if (Session["typeid"] != null&&Session["depart"]!=null)
            {
                string typeid = Session["typeid"].ToString();
                this.hidden2.Value = typeid.Trim();
                //通过typeid查找当前在申报时间内的申报计划编号
                string plancode = project.getPlancode(typeid, DateTime.Now.ToString(), this.ddlPType, this.ddlPLevel, this.labType);
                if (plancode == "none")
                {
                    Response.Redirect("../Error/Error.htm");
                }
                this.hidden1.Value = plancode.Trim();
                //绑定下拉框
                bindDDL();
                getContacts(Session["depart"].ToString(), Session["typeid"].ToString());
            }
            else
                Response.Redirect("../Error/Error.htm");
        }
    }
    /// <summary>
    /// 获取项目管理员和学院管理员的信息
    /// </summary>
    /// <param name="college">学院名称</param>
    /// <param name="typeid">项目类型编号</param>
    protected void getContacts(string college,string typeid)
    {
        StringBuilder sqlstr = new StringBuilder("select [name],telephone,cellphone,email,sex,depart from Sys_Account where depart='");
        sqlstr.Append(college.Trim()).Append("' and usertype=2 select [name],telephone,cellphone,email,sex,depart from Sys_Account ");
        sqlstr.Append("where tid=(select inchargeid from Sys_Guide where id=").Append(typeid).Append(")");
        SqlDataReader myreader = null;
        try
        {
            myreader = PM.Code.DAL.DbHelper.ExecuteDataReaderBySql(sqlstr.ToString());
            if (myreader!=null)
            {
                if (myreader.Read())
                {
                    this.labCName.Text = myreader[0].ToString();
                    this.labCPhone.Text = myreader[1].ToString();
                    this.labCCell.Text = myreader[2].ToString();
                    this.labCEmail.Text = myreader[3].ToString();
                    this.labCCollege.Text = myreader[5].ToString();
                    if (myreader[4].ToString() == "女")
                        Image1.ImageUrl = "~/Images/f11.png";
                }
                myreader.NextResult();
                if(myreader.Read())
                {
                    this.labPName.Text = myreader[0].ToString();
                    this.labPPhone.Text = myreader[1].ToString();
                    this.labPCell.Text = myreader[2].ToString();
                    this.labPEmail.Text = myreader[3].ToString();
                    this.labPCollege.Text = myreader[5].ToString();
                    if (myreader[4].ToString() == "女")
                         Image2.ImageUrl = "~/Images/f11.png";
                }
                myreader.Close();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    //提交
    protected void BtnSubmit_Click(object sender, EventArgs e)
    {
        if (Session["name"] == null)
            Response.Redirect("../Error/Error.htm");
        newproject = new PM.Model.Project();
        SetModel(ref newproject);
        if (this.radStatus.SelectedValue == "1")
        {
            string filepath = "";
            //构建名字
            string no = createFileName(Session["name"].ToString());
            filepath = UpLoadFile(no);
            if (filepath == "1")//大小限制
            {
                PM.Code.Web.alertmessage.ShowMsg("抱歉！文档的大小不能超过4M，请重新上传");
                return;
            }
            else if (filepath == "2")//不是word文档
            {
                PM.Code.Web.alertmessage.ShowMsg("抱歉！只支持上传word格式的文档，请重新上传");
                return;
            }
            else if (filepath == "3")//文件名为空
            {
                PM.Code.Web.alertmessage.ShowMsg("您的文件名为空！请重新上传");
                return;
            }
            else if (filepath == "4")//文件名过长
            {
                PM.Code.Web.alertmessage.ShowMsg("您的文件名过长（超过50个汉字）！请重新上传");
                return;
            }
            else
                newproject.attached = filepath.Trim();
        }
        if (newproject != null)
        {
            if (project.Add(newproject) > 0)
            {
                PM.Code.Web.alertmessage.ShowMsg("您的项目提交成功，请你等待审批！");
                PM.PMSys.log Log = new PM.PMSys.log();
                Log.Insert_Log("提交了一个新项目！",2);
                Server.Transfer("~/User/unapproved.aspx",false);
            }
            else
            {
                PM.Code.Web.alertmessage.ShowMsg("您的项目提交失败！");
                Response.Redirect("~/Error/Error.htm"); 
            }
        }
    }

    protected string createFileName(string tname)
    {
        StringBuilder filename = new StringBuilder();
        string submitdate = DateTime.Now.ToString("yyyy-MM-dd");
        string flag = DateTime.Now.Millisecond.ToString();
        filename.Append("-").Append(tname).Append("-").Append(submitdate).Append("-").Append(flag);
        return filename.ToString();
    }
    /// <summary>
    /// 上传附件（限doc格式）
    /// </summary>
    /// <param name="NO">唯一编号</param>
    /// <returns>返回文件相对路径</returns>
    protected string UpLoadFile(string NO)
    {
        try
        {
            string type = this.labType.Text.Trim();
            int year = DateTime.Now.Year;
            if (!string.IsNullOrEmpty(this.FileUpload1.PostedFile.FileName))
            {
                string checkresult = CheckFile(FileUpload1);
                if (checkresult == "9")
                {
                    string name = this.FileUpload1.FileName;
                    if (name != string.Empty)
                    {
                        string path = Server.MapPath("../ckfinder/userfiles/files" + "//" + type + "//" + year.ToString());//绝对路径
                        if (!System.IO.Directory.Exists(path))
                        {
                            //创建制定文件夹
                            System.IO.Directory.CreateDirectory(path);
                        }
                        string path1 = "../ckfinder/userfiles/files" + "/" + type + "/" + year.ToString(); ;//相对路径
                        name = name.Replace(".doc", "");
                        if (name.Length > 100)
                            return "4";//文件名过长
                        else
                        {
                            path += "/" + name + NO + ".doc";
                            path1 += "/" + name + NO + ".doc";
                            FileUpload1.SaveAs(path);//绝对路径
                            return path1;//数据库中存相对路径
                        }
                    }
                }
                else
                    return checkresult;
            }
            return "3";//文件没有或者名字为空
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    /// <summary>
    /// 验证文件类型
    /// </summary>
    /// <param name="fileName">上传控件</param>
    /// <returns>返回错误</returns>
    public string CheckFile(FileUpload fileName)
    {
        string type = "doc";
        string AllFileName = fileName.PostedFile.FileName;
        string LastFileName = AllFileName.Substring(AllFileName.LastIndexOf(".") + 1).ToLower();
        if (LastFileName == type)
        {
            if (FileUpload1.PostedFile.ContentLength / 1024 / 1024 >= 4)
                return "1";//返回错误1：大小超标
            else
                return "9";//检验合格
        }
        else
            return "2";//返回错误2：不是word文档
    }

    //绑定所有ddl
    protected void bindDDL()
    {
        //绑定教执委
        PM.Code.Web.controlbind.BindDropDownList(this.ddlPCommit, "select * from Dict_Commit where isuse=1 and type=1", "commitee", "id");
        //绑定学科
        PM.Code.Web.controlbind.BindDropDownList(this.ddlSub1, "select distinct subject1 from Dict_Subject where isuse='True'", "subject1", "subject1");
        //绑定学院
        PM.Code.Web.controlbind.BindDropDownList(this.ddlPCollege, "select collegename,collegeid from Dict_College", "collegename", "collegeid");
        this.ddlSub1.SelectedIndex = 0;
        bindSubject2();
    }
    #region ddl触发事件
    protected void ddlPNature_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.ddlPCommit.Items.Clear();
        string value = this.ddlPNature.SelectedValue.Trim();
        string sqlstr = "select * from Dict_Commit where isuse=1 and type=" + value;
        if (value != string.Empty)
            PM.Code.Web.controlbind.BindDropDownList(ddlPCommit, sqlstr, "commitee", "id");
        else
            return;
    }

    protected void ddlSub1_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindSubject2();
    }

    protected void bindSubject2()
    {
        this.ddlSub2.Items.Clear();
        string value = this.ddlSub1.SelectedValue.Trim();
        string sqlstr = "select subject2 from Dict_Subject where isuse='True' and subject1='" + value + "'";
        if (value != string.Empty)
            PM.Code.Web.controlbind.BindDropDownList(ddlSub2, sqlstr, "subject2", "subject2");
        else
            return;
    }
    #endregion
    protected void SetModel(ref PM.Model.Project newproject)
    {
        //赋值project实体类
        newproject.type = this.labType.Text.Trim();
        newproject.ptypeid = this.hidden2.Value;
        newproject.pname = this.txtPName.Text.Trim();
        newproject.zcode = this.txtZCode.Text.Trim();
        newproject.bz = this.txtBZ.Text.Trim();
        newproject.pmanager = Session["tid"].ToString().Trim();
        newproject.builddate = DateTime.Now;
        newproject.status = int.Parse(this.radStatus.SelectedValue.Trim());
        newproject.plevel = this.ddlPLevel.SelectedValue.Trim();
        newproject.pway = this.ddlPWay.SelectedValue.Trim();
        newproject.ptype = this.ddlPType.SelectedValue.Trim();
        newproject.pnature = this.ddlPNature.SelectedValue.Trim();
        newproject.pcommit = this.ddlPCommit.SelectedItem.Text.Trim();
        newproject.sub1 = this.ddlSub1.SelectedItem.Text.Trim();
        newproject.sub2 = this.ddlSub2.SelectedValue.Trim();
        newproject.pcollege = this.ddlPCollege.SelectedItem.Text.Trim();
        newproject.pcode = this.hidden1.Value;
        newproject.yeardue = Int32.Parse(this.ddlYearDue.SelectedValue.Trim());
    }
}
